package com.jianyun.jyzs.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.TripSignAdapter;
import com.jianyun.jyzs.bean.CrmDetial;
import com.jianyun.jyzs.bean.CrmSearchBean;
import com.jianyun.jyzs.bean.CrmSignBean;
import com.jianyun.jyzs.bean.CrmSignDB;
import com.jianyun.jyzs.bean.SignResult;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.CrmSignDao;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.CustomCallback;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.utils.DeviceUtils;
import com.jianyun.jyzs.utils.FullDialogLoading;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.widget.PromptDialog;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import com.jianyun.jyzs.utils.RceLog;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 出差签到
 * Created by yangshijun on 2018/6/4.
 */

public class BussinessTripFragment extends Fragment {
    @BindView(R.id.tag)
    ImageView tag;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_signBtn)
    TextView tvSignBtn;


    private String enterpriseCode;
    private String userId;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption locationOption;
    private FullDialogLoading dialog;
    private AMapLocation aMapLocation = null;
    private CrmSignDao signDao;
    private TripSignAdapter adapter;
    private String crmid;
    private static final int PERMISSON_REQUESTCODE = 0;
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.trip_sign_layout, null);
        ButterKnife.bind(this, view);
        initData();
        return view;
    }

    private void initData() {
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        dialog = FullDialogLoading.createDialog(getActivity());
        dialog.setCancelable(false);
        CrmSearchBean.ListCrm poBean = (CrmSearchBean.ListCrm) getArguments().getSerializable(SysConstant.msg_key_parcelable);
        crmid = poBean.getAutoid() + "";
        signDao = new CrmSignDao(getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new TripSignAdapter(getActivity(), null);
        recyclerView.setAdapter(adapter);
        initGetSignList();
        initLocation();
        tvSignBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (aMapLocation == null) {
                    checkPermisionInitLocation();
                } else {
                    tripSign();
                }
            }
        });
    }

    private void initGetSignList() {
        try {
            List<CrmSignDB> crmSignList = signDao.getCrmSignList(crmid, userId, enterpriseCode);
            if (crmSignList != null && crmSignList.size() > 0) {
                adapter.setList(crmSignList);
            } else {
                //请求服务器
                getSignListData();
            }
        }catch (Exception e){
            e.printStackTrace();
            //请求服务器
            getSignListData();
        }


    }

    private void getSignListData() {
        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        api.getCrmSignList("crm_getsign", userId,crmid,enterpriseCode,
                 "jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onNext(Object o) {
                        try {
                            Gson gson = new Gson();
                            String s = gson.toJson(o);
                            CrmSignBean crmSignBean = gson.fromJson(s, CrmSignBean.class);
                            List<CrmSignBean.Data> data = crmSignBean.getData();
                            if (data!=null&&data.size()>0){
                                for (int i = 0; i < data.size(); i++) {
                                    CrmSignBean.Data bean = data.get(i);
                                    CrmSignDB signDB = new CrmSignDB();
                                    signDB.setEnterpriseCode(enterpriseCode);
                                    signDB.setUserid(userId);
                                    signDB.setLocation(bean.getLable());
                                    String all = bean.getCreateDate().replaceAll("T", " ");
                                    signDB.setTime(all);
                                    signDB.setCrmid(crmid);
                                    signDao.insert(signDB);
                                }
                                refreshRecyclerView();
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        Log.i("test","o:"+o.toString());
                    }
                });
    }

    /**
     * 请求定位权限
     */
    private void checkPermisionInitLocation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkSelfPermission = getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                //没有权限 请求
                requestPermissions(needPermissions, PERMISSON_REQUESTCODE);
            } else {
                dialog.show();
                locationClient.startLocation();
            }
        } else {
            locationClient.startLocation();
        }

    }

    //初始化定位信息
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(getActivity().getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    //默认的定位参数
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    private String[] NETTYPE = {"定位失败", "GPRS", "前次定位结果", "缓存定位结果", "Wifi", "EDGE", "离线定位结果"};//网络类型

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (dialog != null && dialog.isShowing()) dialog.dismiss();
            if (null != location) {
                if (location.getErrorCode() == 0) {
                    aMapLocation = location;
                    tripSign();
                } else {
                    PromptDialog.newInstance(getActivity(), "提示", "定位失败" + location.getErrorCode()).show();
                }
            } else {
                PromptDialog.newInstance(getActivity(), "提示", "定位失败").show();
            }
        }
    };


    /**
     * 出差签到
     */
    private void tripSign() {
        if (!dialog.isShowing()) dialog.show();
        Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        HashMap<String, String> map = new HashMap<>();
        final String label = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();
        String deviceid = DeviceUtils.getAndroidID(getActivity());
        String netType = NETTYPE[aMapLocation.getLocationType()];
        String userIP = NetUtil.getLocalIpAddress();
        map.put("method", "SignWaiQin");
        map.put("EnterpriseCode", enterpriseCode);
        map.put("employeeId", userId);
        map.put("location_X", aMapLocation.getLatitude() + "");
        map.put("location_Y", aMapLocation.getLongitude() + "");
        map.put("scale", "5");
        map.put("label", label);
        map.put("deviceId", deviceid);
        map.put("netType", netType);
        map.put("crmId", crmid);
        map.put("platFormInfo", "Android");
        map.put("userIp", userIP);
        map.put("sourceSystem", "jyzs");
        map.put("appCode","jyzs");
        map.put("appType","Android");
        map.put("appVersion","1.0.2");
        api.crmSign(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CustomCallback<SignResult>() {
                    @Override
                    protected void onResponse(final SignResult response) {
                        RceLog.d("lml", response.toString());
                        if (response.isResult()) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    CrmSignDB signDB = new CrmSignDB();
                                    signDB.setEnterpriseCode(enterpriseCode);
                                    signDB.setUserid(userId);
                                    signDB.setLocation(label);
                                    signDB.setTime(response.getSignTime());
                                    signDB.setCrmid(crmid);
                                    signDao.insert(signDB);
                                    refreshRecyclerView();
                                }
                            });
                            dialog.dismiss();

                        }
                    }

                    @Override
                    protected void onException(String msg) {
                        RceLog.d("lml", "onException" + msg);
                        dialog.dismiss();
                    }
                });
    }

    private void refreshRecyclerView() {
        List<CrmSignDB> crmSignList = signDao.getCrmSignList(crmid, userId, enterpriseCode);
        RceLog.d("lml", crmSignList.toString());
        if (crmSignList != null && crmSignList.size() > 0) {
            adapter.setList(crmSignList);
            recyclerView.scrollToPosition(crmSignList.size() - 1);
        }
    }

}
